import { getFetch } from '@/utils/doFetch';
import { CloseOutlined, EllipsisOutlined, EnterOutlined, LoadingOutlined, MinusOutlined, PlusOutlined, TagFilled, TagOutlined } from '@ant-design/icons';
import { useRequest } from 'ahooks';
import { Popover, Tag, theme, Input, Empty, Button, Tooltip, ColorPicker, message, Divider } from 'antd';
import React, { useState, useEffect, useRef } from 'react';

const ChooseTag = ({ item, checked, setChecked, addon, setAddon, actionRef }) => {
  const { token } = theme.useToken();
  //查询当前项目下的所有标签
  const { data, loading, refresh } = useRequest(
    async () => {
      if (!item.projectId) {
        return [];
      }
      let res = await getFetch({
        url: '/projectTag',
        params: {
          projectId: item?.projectId,
        },
      });
      return res?.data?.dataList;
    },
    {
      refreshDeps: [item?.projectId],
      onSuccess: () => {
        setAddon([])
      }
    },
  );

  useEffect(() => {
    actionRef.current = {
      refresh
    };
  }, [actionRef]);


  return (
    <div className='center' style={{ width: "100%", flexWrap: "wrap" }}>
      {
        loading ?
          <div className="sorts">
            <LoadingOutlined />
          </div>
          :
          data?.length === 0 && addon.length === 0 ?
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            :
            <div style={{ paddingTop: 4, display: "flex", justifyContent: 'flex-start', gap: 0, width: "100%", flexWrap: "wrap" }}>
              {data?.map?.((tag, index) => {
                const isLongTag = tag?.name?.length > 8;
                const tagElem = (
                  <Tag
                    key={tag.name}
                    style={{
                      cursor: 'pointer',
                      color: checked.includes(tag.id) ? "#fff" : tag.color,
                      backgroundColor: checked.includes(tag.id) ? (tag.color ? tag.color : token.colorPrimary) : "transparent",
                      marginBottom: 4
                    }}
                    onClick={() => {
                      let curtags = checked;
                      if (curtags.includes(tag.id)) {
                        curtags = curtags.filter(curtag => curtag !== tag.id);
                      } else {
                        curtags = [...curtags, tag.id];
                      }
                      setChecked(curtags)
                    }}
                    bordered={false}
                  >
                    <span>
                      {isLongTag ? `${tag.name.slice(0, 8)}...` : tag.name}
                    </span>
                  </Tag>
                );
                return isLongTag ? (
                  <Tooltip title={tag.name} key={tag.name}>
                    {tagElem}
                  </Tooltip>
                ) : (
                  tagElem
                );
              })}

              {
                addon && addon.map?.((tag, index) => {
                  const isLongTag = tag?.name?.length > 8;
                  const tagElem = (
                    <Tag
                      key={tag.name}
                      style={{
                        cursor: 'pointer',
                        color: "#fff",
                        backgroundColor: tag.color ? tag.color : token.colorPrimary,
                        marginBottom: 4
                      }}
                      closable
                      onClose={(e) => {
                        setAddon(addon.filter(it => it.name !== tag.name))
                      }}
                      closeIcon={<CloseOutlined style={{ color: "#fff" }} />}
                      bordered={false}
                    >
                      <span>
                        {isLongTag ? `${tag.name.slice(0, 8)}...` : tag.name}
                      </span>
                    </Tag>
                  );
                  return isLongTag ? (
                    <Tooltip title={tag.name} key={tag.name}>
                      {tagElem}
                    </Tooltip>
                  ) : (
                    tagElem
                  );
                })

              }


            </div>
      }
    </div>
  )

};



const TagList = ({ item, limit, canedit = false, changeList, loading }) => {
  const { token } = theme.useToken();
  const [checked, setChecked] = useState([]);
  const [addon, setAddon] = useState([]);

  const [curcolor, setCurcolor] = useState(token.colorPrimary);
  const [text, setText] = useState();

  useEffect(() => {
    setChecked(item?.itemTagList?.map(tag => tag.projectTagId))
  }, [item?.itemTagList]);

  const [open, setOpen] = useState(false);
  const actionRef = useRef();

  const content = <div className='columns' style={{ width: 258 }}>
    <b>新增标签</b>
    <div className="spread" style={{ gap: 0, backgroundColor: token.colorBorder, padding: 6,paddingLeft:9, borderRadius: 6, marginTop: 12 }}>
      <ColorPicker
        size='small'
        presets={[
          {
            label: "预设颜色",
            colors: [token.colorPrimary, token.colorInfo, token.colorSuccess, token.colorWarning, token.colorError, "#ff0000", 'purple', 'dark', 'green', '#13c2c2',]
          }
        ]}
        value={curcolor}
        onChange={(value, hex) => {
          setCurcolor(hex)
        }}
      ></ColorPicker>
      <Input
        variant='borderless'
        placeholder='标签名称 按 Enter 添加'
        suffix={<EnterOutlined />}
        value={text}
        onChange={e => {
          setText(e.target.value)
        }}
        onPressEnter={(e) => {
          if (addon.map(it => it.name).includes(e.target.value) || item?.itemTagList.map(it => it.name).includes(e.target.value)) {
            message.error("已存在相同名称的标签");
            return;
          }
          setAddon(s => ([
            ...s,
            {
              name: e.target.value,
              color: curcolor,
            }
          ]))
          setText(null);
        }}
      ></Input>
    </div>
    <Divider style={{ margin: '12px 0 12px 0' }}></Divider>
    <b>选择标签</b>
    <div className="centerl element" style={{ width: "100%", maxHeight: 240, marginTop: 8, paddingBottom: 6 }}>
      <ChooseTag actionRef={actionRef} item={item} checked={checked} setChecked={setChecked} addon={addon} setAddon={setAddon}></ChooseTag>
    </div>
    <Divider style={{ margin: '0px 0 12px 0' }}></Divider>
    <Button type='primary' loading={loading} size='small' onClick={async () => {
      const params = checked.map(it => ({ id: it }));
      const result = [...params, ...addon.map(it => ({ name: it.name, color: it.color }))];
      await changeList(result)
      actionRef?.current?.refresh();
    }}>
      确定
    </Button>
  </div>



  return <div className='centerl'>
    {item?.itemTagList
      ?.filter((it, i) => i < limit)
      .map((it) => {
        const isLongTag = it?.name?.length > 4;
        return (
          <Tag key={it?.id} color={it?.color} bordered={false}>
            <span style={{ fontSize: 12 }} title={it?.name}>{isLongTag ? `${it?.name?.slice(0, 4)}...` : it.name}</span>
          </Tag>
        );
      })}
    {item?.itemTagList?.length > limit && (
      <Popover
        content={
          <div>
            {item?.itemTagList
              ?.filter((it, i) => i > limit - 1)
              .map((it) => {
                const isLongTag = it?.name?.length > 4;
                return (
                  <Tag key={it?.id} color={it?.color}
                    bordered={false}
                  >
                    <span style={{ fontSize: 12 }}>
                      {isLongTag ? `${it?.name?.slice(0, 4)}..` : it.name}
                    </span>
                  </Tag>
                );
              })}
          </div>
        }
      >
        <Tag
          icon={<EllipsisOutlined />}
          bordered={false}
        />
      </Popover>
    )}
    {
      item?.itemTagList?.length === 0 && <Tag bordered={false}><span style={{ opacity: 0.5 }}>/</span></Tag>
    }
    {
      !canedit || !item?.projectId ? null : <Popover
        open={open}
        trigger={'click'}
        content={content}
        placement='bottomRight'
        onOpenChange={setOpen}
      >
        <div className="sort"
          style={{ padding: "0 4px", cursor: "pointer" }}
        >
          <TagFilled style={{ color: open ? token.colorPrimary : token.colorText, fontSize: 16 }} />
        </div>
      </Popover>
    }

  </div>


};

export default TagList;
